﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Repid.Utility.Helper
{
    public class ExpressionHelper
    {
        /// <summary>
        /// 动态创建Selector
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <returns></returns>
        public static Expression<Func<TSource, TResult>> CreateSelector<TSource, TResult>()
        {
            var type = typeof(TResult);

            var properties = type.GetProperties();

            var bindingList = new List<MemberBinding>();

            var left = Expression.Parameter(typeof(TSource), "m");

            foreach (var item in properties)
            {
                MemberInfo mi = type.GetMember(item.Name)[0];

                MemberExpression me = Expression.Property(left, item.Name);

                MemberBinding mb = Expression.Bind(mi, me);

                bindingList.Add(mb);
            }

            var body = Expression.MemberInit(Expression.New(type), bindingList);

            return (Expression<Func<TSource, TResult>>)Expression.Lambda(body, left);
        }
    }
}
